import React, { useEffect, useCallback, useState, useMemo } from 'react';
import { Typography, Space, Card, Pagination, Divider } from 'antd';
import { UserOutlined, IdcardOutlined, DollarOutlined } from '@ant-design/icons';
import type { IfCheckitem } from '../types/checkitem';
const { Title, Text, Paragraph } = Typography;
import http from '../api/http';

// 定义组件接收的属性类型
interface FcheckitemProps {
  selectedId?: number;
}

// 分页参数接口
interface PaginationParams {
  current: number;
  pageSize: number;
  total: number;
}

// 卡片样式配置（集中管理，便于后续修改）
const cardStyles = {
  container: {
    display: 'grid',
    gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
    gap: 20,
    marginBottom: 24,
    padding: '0 8px',
  } as React.CSSProperties,
  card: {
    transition: 'all 0.3s ease',
    boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
    '&:hover': {
      boxShadow: '0 4px 16px rgba(0, 0, 0, 0.12)',
      transform: 'translateY(-2px)',
    },
  } as React.CSSProperties,
  infoItem: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: 8,
    fontSize: 14,
  } as React.CSSProperties,
  infoLabel: {
    color: '#666',
    width: 80,
    display: 'inline-block',
  } as React.CSSProperties,
  infoValue: {
    flex: 1,
    color: '#333',
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  } as React.CSSProperties,
  priceTag: {
    color: '#ff4d4f',
    fontWeight: 500,
  } as React.CSSProperties,
  idBadge: {
    backgroundColor: '#f0f7ff',
    color: '#1890ff',
    padding: '2px 8px',
    borderRadius: 4,
    fontSize: 12,
    display: 'flex',
    alignItems: 'center',
  } as React.CSSProperties,
};

const Fcheckitem: React.FC<FcheckitemProps> = ({ selectedId }) => {
  const [data, setdata] = useState<Array<IfCheckitem>>([]);
  const [pagination, setPagination] = useState<PaginationParams>({
    current: 1,
    pageSize: 3,
    total: 0,
  });

  // 计算当前页价格总和（保留原功能）
  const currentPageTotal = useMemo(() => {
    return data.reduce((sum, item) => {
      const price = Number(item.price) || 0;
      return sum + price;
    }, 0);
  }, [data]);

  // 搜索函数（逻辑不变，适配卡片数据渲染）
  const search = useCallback(() => {
    http.get<{ data: IfCheckitem[], total: number }>("Tcimpact/findPage", {
      id: selectedId || 5,
      page: pagination.current,
      size: pagination.pageSize
    }).then(res => {
      setdata(res.data);
      setPagination(prev => ({
        ...prev,
        total: res.count || 0,
      }));
    });
  }, [selectedId, pagination.current, pagination.pageSize]);

  // 分页变化处理（逻辑不变）
  const handlePaginationChange = (page: number, pageSize: number) => {
    setPagination(prev => ({
      ...prev,
      current: page,
      pageSize,
    }));
  };

  // 初始加载和参数变化时重新请求（逻辑不变）
  useEffect(() => {
    search();
  }, [search]);

  return (
    <>
      {/* 1. 价格统计区域（保留并优化样式） */}
      <div style={{ margin: '16px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <Title level={5} style={{ margin: 0 }}>检查项列表</Title>
        <div>
          <Text strong type="primary" style={{ fontSize: 16 }}>
            <DollarOutlined /> 当前页总价：¥{currentPageTotal.toFixed(2)}
          </Text>
        </div>
      </div>

      {/* 2. 卡片列表区域（核心替换部分） */}
      <div style={cardStyles.container}>
        {data.length > 0 ? (
          data.map((item) => (
            <Card
              key={item.id}
              title={
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text strong style={{ fontSize: 16 }}>{item.name}</Text>
                  {/* 用自定义样式的div替代Tag组件 */}
                  <div style={cardStyles.idBadge}>
                    <IdcardOutlined style={{ fontSize: 12, marginRight: 4 }} />
                    编号：{item.id}
                  </div>
                </div>
              }
              style={cardStyles.card}
              bordered={true}
            >
              {/* 卡片内容：基础信息列表 */}
              <div>
                {/* 适用性别 */}
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>
                    <UserOutlined style={{ marginRight: 4 }} /> 适用性别
                  </span>
                  <span style={cardStyles.infoValue}>{item.sex || '未设置'}</span>
                </div>

                {/* 检查类型（移除ListOutlined，仅保留文字） */}
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>检查类型</span>
                  <span style={cardStyles.infoValue}>{item.affiliationClassify || '未分类'}</span>
                </div>

                {/* 价格（突出显示） */}
                <div style={cardStyles.infoItem}>
                  <span style={cardStyles.infoLabel}>
                    <DollarOutlined style={{ marginRight: 4 }} /> 价格
                  </span>
                  <span style={{ ...cardStyles.infoValue, ...cardStyles.priceTag, fontSize: 15 }}>
                    ¥{Number(item.price).toFixed(2)}
                  </span>
                </div>
              </div>

              {/* 卡片底部分割线（可选，增强视觉层次） */}
              <Divider style={{ margin: '12px 0 0 0' }} />
            </Card>
          ))
        ) : (
          // 空数据提示
          <div style={{ gridColumn: '1/-1', textAlign: 'center', padding: '60px 0' }}>
            <Text type="secondary">暂无检查项数据</Text>
          </div>
        )}
      </div>

      {/* 3. 分页控制区域（保留原功能，优化位置） */}
      <div style={{ display: 'flex', justifyContent: 'center', marginTop: 16 }}>
        <Pagination
          current={pagination.current}
          pageSize={pagination.pageSize}
          total={pagination.total}
          showSizeChanger
          showQuickJumper
          showTotal={(total) => `共 ${total} 条记录`}
          pageSizeOptions={['3', '5', '10', '20']}
          onChange={handlePaginationChange}
          onShowSizeChange={handlePaginationChange}
        />
      </div>
    </>
  );
};

export { Fcheckitem };